package com.gking.centerSystem.service.Roles;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gking.centerSystem.common.BaseContext;
import com.gking.centerSystem.common.ProgramException;
import com.gking.centerSystem.common.Result;
import com.gking.centerSystem.entity.Permissions;
import com.gking.centerSystem.entity.Roles;
import com.gking.centerSystem.entity.Sort;
import com.gking.centerSystem.mapper.RolesMapper;
import com.gking.centerSystem.service.Sort.SortService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles> implements RolesService {

    @Autowired
    private SortService sortService;

    @Resource
    private RolesMapper rolesMapper;

    /**
     * 通过一个分类id找出该分类下的所有分类id
     *
     * @param id 分类id
     * @return s
     */
    private List<String> getIds(String id) {
        List<String> idList = new ArrayList<>();
        idList.add(id);

        // 将分类下的所有权限分类id查找出来
        LambdaQueryWrapper<Sort> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Sort::getParentId, id);
        queryWrapper.eq(Sort::getIsDelete, 0);
        queryWrapper.eq(Sort::getType, "role");
        List<Sort> sorts = sortService.list(queryWrapper);

        // 递归找出所有id
        for (Sort sort : sorts) idList.addAll(getIds(sort.getId()));
        return idList;
    }

    /**
     * 获取角色列表
     *
     * @param sortId    分类id
     * @param isDefault 是否默认
     * @param realName  角色名称
     * @param size      分页大小
     * @param page      分页页码
     * @return s
     */
    @Override
    public Result<Page> getRolesList(String sortId, Integer isDefault, String realName, Integer size, Integer page) {

        if (Objects.equals(sortId, "")) sortId = null;
        if (size == null) size = 20;
        if (page == null) page = 1;
        if (isDefault != null && isDefault != 0 && isDefault != 1) return Result.error("isDefault参数错误");

        try {
            List<String> ids = new ArrayList<>();
            if (sortId != null) { //是否为条件查询
                ids = new ArrayList<>(new HashSet<>(getIds(sortId)));
            }

            Page<Roles> pageInfo = new Page<>(page, size);
            Page<Roles> pageResult = rolesMapper.getRolesList(pageInfo, ids, isDefault, realName);

            return Result.success("获取角色列表成功！", pageResult);
        } catch (Exception e) {
            log.error("获取角色列表失败！{}", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 创建角色或者修改角色信息
     *
     * @param name        角色
     * @param realName    角色名称
     * @param description 描述
     * @param sortId      分类id
     * @param isDefault   是否为用户默认角色
     * @param roleId      角色id
     * @return s
     */
    @Override
    public Result<String> setRole(String name, String realName, String description,
                                  String sortId, Integer isDefault, String roleId) {

        if (name.isEmpty() || realName.isEmpty() || description.isEmpty() || sortId.isEmpty())
            return Result.error("请将参数补充完整");

        if (Objects.equals(roleId, "")) roleId = null;
        if (isDefault != null && isDefault != 0 && isDefault != 1)
            return Result.error("isDefault参数错误");

        try {
            Sort s = sortService.getById(sortId);
            if (s == null) return Result.error("分类不存在！");
            if (!Objects.equals(s.getType(), "role")) return Result.error("该分类不是角色分类！");

            Roles roles = new Roles();
            roles.setName(name);
            roles.setRealName(realName);
            roles.setDescription(description);
            roles.setSortId(sortId);
            if (isDefault != null) roles.setIsDefault(isDefault);
            roles.setUpdateTime(LocalDateTime.now());
            roles.setUpdateUserId(BaseContext.getCurrentId());
            roles.setSystemCode(s.getSystemCode());

            //权限id不存在则创建
            if (roleId == null) {
                roles.setCreateUserId(BaseContext.getCurrentId());
                this.save(roles);
                return Result.success("创建角色成功！");
            }
            //权限id存在则更新
            roles.setId(roleId);
            this.updateById(roles);
            return Result.success("修改角色成功！");
        } catch (Exception e) {
            log.error("创建角色失败！{}", e.getMessage());
            throw new ProgramException();
        }
    }

    /**
     * 批量删除角色
     *
     * @param roleIdList 角色id列表
     * @return s
     */
    @Transactional
    @Override
    public Result<String> deleteRoles(List<String> roleIdList) {
        try {
            if (roleIdList.isEmpty()) return Result.error("请选择要删除的角色");

            LambdaUpdateWrapper<Roles> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Roles::getIsDelete, 1);
            updateWrapper.set(Roles::getDeleteUserId, BaseContext.getCurrentId());
            updateWrapper.set(Roles::getDeleteTime, LocalDateTime.now());
            updateWrapper.in(Roles::getId, roleIdList);

            this.update(updateWrapper);
            return Result.success("删除角色成功！");
        } catch (Exception e) {
            log.error("删除角色失败！{}", e.getMessage());
            throw new ProgramException();
        }
    }


    /**
     * 批量更新角色状态
     *
     * @param roleIdList 角色id 列表
     * @param status     状态 0启用，1禁用
     * @return s
     */
    @Transactional
    @Override
    public Result<String> updateRolesStatus(List<String> roleIdList, Integer status) {
        try {
            if (roleIdList.isEmpty() || status == null) return Result.error("请将参数补充完整");
            if (status < 0 || status > 1) return Result.error("状态参数错误");

            LambdaUpdateWrapper<Roles> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Roles::getEnable, status);
            updateWrapper.set(Roles::getUpdateUserId, BaseContext.getCurrentId());
            updateWrapper.set(Roles::getUpdateTime, LocalDateTime.now());
            updateWrapper.in(Roles::getId, roleIdList);
            this.update(updateWrapper);
            return Result.success("更新角色状态成功！");
        } catch (Exception e) {
            log.error("更新角色状态失败！{}", e.getMessage());
            throw new ProgramException();
        }
    }
}
